package com.base_data_handler.sx.handler;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.dbutils.QueryRunner;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.base_data_handler.utils.Constant;
import com.base_data_handler.utils.DBUtil;
import com.base_data_handler.utils.DataSourceUtils;
import com.base_data_handler.utils.HttpUtils;
import com.base_data_handler.utils.StringUtils;
/**
 * cimmiss  全国城镇精细化预报产品要素资料 
 * @param urlStr
 * @return
 */
public class SX_Forcast_Handler  {
//	private	static QueryRunner qr=new QueryRunner(DruidPlugin.getDataSource());
	private	static QueryRunner qr=new QueryRunner(DataSourceUtils.getDatasSource());;

	
	public static boolean getCimmisSX_forcast() throws SQLException{
		String times="";//20170627000000
		Calendar c=Calendar.getInstance();
		int year=c.get(Calendar.YEAR);
		String month=(c.get(Calendar.MONTH)+1)+"";
		String day=c.get(Calendar.DAY_OF_MONTH)+"";
		String hour=c.get(Calendar.HOUR_OF_DAY)+"";
		
		if(month.length()==1)month="0"+month;
		if(day.length()==1)day="0"+day;
		
//		System.out.println("year="+year+",month="+month+",day="+day);
		times=year+month+day+"000000";
			 
		String url="http://"+Constant.CMISS_HOST_PORT+"/cimiss-web/api";
//		String param="userId="+Constant.CMISS_NAME+"&pwd="+Constant.CMISS_PASS+"&interfaceId=getSevpWefcRffcByTime&dataCode=SEVP_CHN_WEFC_RFFC&elements=Station_Name,Province,City,Cnty,Town,Station_Id_C,Station_Id_d,Lat,Lon,Alti,Admin_Code_CHN,Year,Mon,Day,Hour,Validtime,TEM,RHU,WIN_D,WIN_S,PRS,PRE_PRE_Fore,CLO_Cov_Low,WEP,VIS&time="+times+"&dataFormat=json&eleValueRanges=Province:陕西省,甘肃省;;Day:"+day+";Hour:0;&orderBy=Hour:desc";
		
		String param="userId="+Constant.CMISS_NAME+"&pwd="+Constant.CMISS_PASS+"&interfaceId=getSevpWefcRffcByTime&dataCode=SEVP_CHN_WEFC_RFFC&elements=Station_Name,Province,City,Cnty,Town,Station_Id_C,Station_Id_d,Lat,Lon,Alti,Admin_Code_CHN,Year,Mon,Day,Hour,Validtime,TEM,RHU,WIN_D,WIN_S,PRS,PRE_PRE_Fore,CLO_Cov_Low,WEP,VIS&time="+times+"&dataFormat=json&eleValueRanges=Day:"+day+";Hour:0;&orderBy=Hour:desc";
		Map<String, String> map=new HashMap<String, String>();
		String[] key_value = param.split("&");
		for (int i = 0; i < key_value.length; i++) {
			String[] k_v = key_value[i].split("=");
			map.put(k_v[0], k_v[1]);
		 }
		System.out.println(url+"?"+param);
		 String str = HttpUtils.sendHttpClientPost(url, map, "utf-8");
		 //纯jdbc实现
		  savaBatch(str) ;
		  
//		 System.out.println(str);
//		 System.out.println(url+"?"+param);
//		 QuryNerBatch(str);
		 return false;
	}

	private static void QuryNerBatch(String str) throws SQLException {
		JSONObject alljson= (JSONObject) JSON.parse(str);
		 
		 if(alljson.getString("returnCode").equals("0")){
			  JSONArray mod = JSON.parseArray(alljson.getString("DS"));
				Object[][] params=new Object[mod.size()][38];
			   JSONObject obj=null;
			
			   for (int i = 0; i < mod.size(); i++) {
				    obj = (JSONObject) mod.get(i);
				    if(StringUtils.isEmpty(obj.getString("Station_Name"))||
				       StringUtils.isEmpty(obj.getString("Cnty"))) continue;
//				    System.out.println(mod.get(i));
				    params[i][0]=obj.getString("Station_Name");
				    params[i][1]=obj.getString("Province");
				    params[i][2]=obj.getString("City");
				    params[i][3]=obj.getString("Cnty");
				    params[i][4]=obj.getString("Town");
				    params[i][5]=obj.getString("Station_Id_C");
				    params[i][6]=obj.getString("Lat");
				    params[i][7]=obj.getString("Lon");
				    params[i][8]=obj.getString("Alti");
				    params[i][9]=obj.getString("Admin_Code_CHN");
				    params[i][10]=obj.getString("Year");
				    params[i][11]=obj.getString("Mon");
				    params[i][12]=obj.getString("Day");
				    params[i][13]=obj.getString("Hour");
				    params[i][14]=obj.getString("Validtime");
				    
				    String tem="0";
				    
				    if(obj.getString("TEM")!=null&&!obj.getString("TEM").contains("99999")){
				    	tem=obj.getString("TEM");
				    }
				    params[i][15]=tem;
				    
				    String rhu="0";
				    if(obj.getString("RHU")!=null&&!obj.getString("RHU").contains("99999")){
				    	rhu=obj.getString("RHU");
				    }
				    params[i][16]=rhu;
				    		
				    String win_d="0";
				    if(obj.getString("WIN_D")!=null&&!obj.getString("WIN_D").contains("99999")){
				    	win_d=obj.getString("WIN_D");
				    }
				    params[i][17]=win_d;
				    
				    String win_s="0";
				    if(obj.getString("WIN_S")!=null&&!obj.getString("WIN_S").contains("99999")){
				    	win_s=obj.getString("WIN_S");
				    }
				    params[i][18]=win_s;
				    
				    String prs="0";
				    if(obj.getString("PRS")!=null&&!obj.getString("PRS").contains("99999")){
				    	prs=obj.getString("PRS");
				    }
				    params[i][19]=prs;
				    
				    String pre_pre_fore="0";
				    if(obj.getString("PRE_PRE_Fore")!=null&&!obj.getString("PRE_PRE_Fore").contains("99999")){
				    	pre_pre_fore=obj.getString("PRE_PRE_Fore");
				    }
				    params[i][20]=pre_pre_fore;
				    
				    String clo_cov_low="0";
				    if(obj.getString("CLO_Cov_Low")!=null&&!obj.getString("CLO_Cov_Low").contains("99999")){
				    	clo_cov_low =obj.getString("CLO_Cov_Low");
				    }
				    params[i][21]=clo_cov_low;
				    
				    String wep="0";
				    if(obj.getString("WEP")!=null&&!obj.getString("WEP").contains("99999")){
				    	wep=obj.getString("WEP");
				    }
				    params[i][22]=wep;
				    
				    String vis="0";
				    if(obj.getString("VIS")!=null&&!obj.getString("VIS").contains("99999")){
				    	vis=obj.getString("VIS");
				    }
				    params[i][23]=vis;
				    params[i][24]=obj.getString("Station_Id_C")+obj.getString("Day")+obj.getString("Hour")+obj.getString("Validtime");
				    params[i][25]=obj.getString("Year");
				    params[i][26]=obj.getString("Mon");
				    params[i][27]=obj.getString("Day");
				    params[i][28]=obj.getString("Hour");
				    
				    params[i][29]=tem;
				    params[i][30]=rhu;
				    params[i][31]=win_d;
				    params[i][32]=win_s;
				    params[i][33]=prs;
				    params[i][34]=pre_pre_fore;
				    params[i][35]=clo_cov_low;
				    params[i][36]=wep;
				    params[i][37]=vis;
			    }
			   proData2Db(params); 
			  
			 
		 }
	}
	
	private static void proData2Db(Object[][] params) throws SQLException{
		StringBuilder sql=new StringBuilder();

		sql.append("INSERT INTO   cmiss_focast ")
		  .append("( Station_Name,Province,City,Cnty,Town,Station_Id_C,Lat,Lon,Alti,Admin_Code_CHN,Year,Mon,Day,Hour,Validtime,TEM,RHU,WIN_D,WIN_S,PRS,PRE_PRE_Fore,CLO_Cov_Low,WEP,VIS,id) ")
		  .append(" VALUES (?, ?, ?, ? , ? ,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)")			
		  .append(" ON DUPLICATE KEY UPDATE  ")
		  .append(" Year=?,Mon=?,Day=?,Hour=?,TEM =?,RHU=?,WIN_D=?,WIN_S=?")
		  .append( ",PRS=?,PRE_PRE_Fore=?,CLO_Cov_Low=?,WEP=?,VIS=?");//批量
		qr.batch(sql.toString(), params);
	}
	public static void main(String[] args) throws SQLException {
		try {
			 getCimmisSX_forcast();
//			   System.out.println("需要循环"+excuttime);
		} catch (Exception e) {
			e.printStackTrace();
		}
//		
	}
	
	
    public static void savaBatch(String str){
     	  PreparedStatement ps = null;
     		 DBUtil db = null;
     		 Connection co = null;
     		 int rs = 0;
     		StringBuilder sql=new StringBuilder();
     		sql.append("INSERT INTO   cmiss_focast ")
	   		  .append("( Station_Name,Province,City,Cnty,Town,Station_Id_C,Lat,Lon,Alti,Admin_Code_CHN,Year,Mon,Day,Hour,Validtime,TEM,RHU,WIN_D,WIN_S,PRS,PRE_PRE_Fore,CLO_Cov_Low,WEP,VIS,id,create_time) ")
	   		  .append(" VALUES (?, ?, ?, ? , ? ,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,now())")			
	   		  .append(" ON DUPLICATE KEY UPDATE  ")
	   		  .append(" Year=?,Mon=?,Day=?,Hour=?,TEM =?,RHU=?,WIN_D=?,WIN_S=?")
	   		  .append( ",PRS=?,PRE_PRE_Fore=?,CLO_Cov_Low=?,WEP=?,VIS=?,create_time=now()");//批量
     		 db = new DBUtil();
     		 try { 
     			co=db.getConnection();
 				co.setAutoCommit(false);
 				ps = co.prepareStatement(sql.toString());
 				 JSONObject alljson= (JSONObject) JSON.parse(str);
 				if(alljson.getString("returnCode").equals("0")){
					  JSONArray mod = JSON.parseArray(alljson.getString("DS"));
					   JSONObject obj=null;
					  System.out.println("共有："+mod.size());
					  int j=0;
					   for (int i = 0; i < mod.size(); i++) {
						    obj = (JSONObject) mod.get(i);
						    if(StringUtils.isEmpty(obj.getString("Station_Name"))||
						       StringUtils.isEmpty(obj.getString("Cnty"))) continue;
//						    System.out.println(mod.get(i));
						    ps.setString(1, obj.getString("Station_Name"));
						    ps.setString(2,obj.getString("Province"));
						    ps.setString(3,obj.getString("City"));
						    ps.setString(4,obj.getString("Cnty"));
						    ps.setString(5,obj.getString("Town"));
						    ps.setString(6,obj.getString("Station_Id_C"));
						    ps.setString(7,obj.getString("Lat"));
						    ps.setString(8,obj.getString("Lon"));
						    ps.setString(9,obj.getString("Alti"));
						    ps.setString(10,obj.getString("Admin_Code_CHN"));
						    ps.setString(11,obj.getString("Year"));
						    ps.setString(12,obj.getString("Mon"));
						    ps.setString(13,obj.getString("Day"));
						    ps.setString(14,obj.getString("Hour"));
						    ps.setString(15,obj.getString("Validtime"));
						    
						    String tem="0";
						    
						    if(obj.getString("TEM")!=null&&!obj.getString("TEM").contains("99999")){
						    	tem=obj.getString("TEM");
						    }
						    ps.setString(16,tem);
						    
						    String rhu="0";
						    if(obj.getString("RHU")!=null&&!obj.getString("RHU").contains("99999")){
						    	rhu=obj.getString("RHU");
						    }
						    ps.setString(17,rhu);
						    		
						    String win_d="0";
						    if(obj.getString("WIN_D")!=null&&!obj.getString("WIN_D").contains("99999")){
						    	win_d=obj.getString("WIN_D");
						    }
						    ps.setString(18,win_d);
						    
						    String win_s="0";
						    if(obj.getString("WIN_S")!=null&&!obj.getString("WIN_S").contains("99999")){
						    	win_s=obj.getString("WIN_S");
						    }
						    ps.setString(19,win_s);
						    
						    String prs="0";
						    if(obj.getString("PRS")!=null&&!obj.getString("PRS").contains("99999")){
						    	prs=obj.getString("PRS");
						    }
						    ps.setString(20,prs);
						    
						    String pre_pre_fore="0";
						    if(obj.getString("PRE_PRE_Fore")!=null&&!obj.getString("PRE_PRE_Fore").contains("99999")){
						    	pre_pre_fore=obj.getString("PRE_PRE_Fore");
						    }
						    ps.setString(21,pre_pre_fore);
						    
						    String clo_cov_low="0";
						    if(obj.getString("CLO_Cov_Low")!=null&&!obj.getString("CLO_Cov_Low").contains("99999")){
						    	clo_cov_low =obj.getString("CLO_Cov_Low");
						    }
						    ps.setString(22,clo_cov_low);
						    
						    String wep="0";
						    if(obj.getString("WEP")!=null&&!obj.getString("WEP").contains("99999")){
						    	wep=obj.getString("WEP");
						    }
						    ps.setString(23,wep);
						    
						    String vis="0";
						    if(obj.getString("VIS")!=null&&!obj.getString("VIS").contains("99999")){
						    	vis=obj.getString("VIS");
						    }
						    ps.setString(24,vis);
						    ps.setString(25,obj.getString("Station_Id_C")+obj.getString("Day")+obj.getString("Hour")+obj.getString("Validtime"));
						    ps.setString(26,obj.getString("Year"));
						    ps.setString(27,obj.getString("Mon"));
						    ps.setString(28,obj.getString("Day"));
						    ps.setString(29,obj.getString("Hour"));
						    
						    ps.setString(30,tem);
						    ps.setString(31,rhu);
						    ps.setString(32,win_d);
						    ps.setString(33,win_s);
						    ps.setString(34,prs);
						    ps.setString(35,pre_pre_fore);
						    ps.setString(36,clo_cov_low);
						    ps.setString(37,wep);
						    ps.setString(38,vis);
						   ps.addBatch();
						   j=i;
						     if(i%1000==0){
							    ps.executeBatch();
								co.commit();
							    ps.clearParameters();
				                ps.clearBatch();
				            	
							 }
					    }
				
			System.out.println("执行了："+j);
				ps.executeBatch();
				co.commit();
				ps.clearParameters();
                ps.clearBatch();
             System.out.println("提交了事务");
               
               }
     		 }catch (SQLException e) {
     			 	e.printStackTrace();
     		  }finally{
					try {
						if (co!=null)
						co.close();
						if (ps!=null)
	   						ps.close();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
	         }
    }
 }
